package adb

import (
	log2 "answer5/log"
	"github.com/golang/freetype"
	"image"
	"image/draw"
	"image/jpeg"
	"io/ioutil"
	"log"
	"math"
	"os"
	"strings"
)

func CreateQuestionImage(title *string,options *[]string) image.Image{
	go log2.LogPrint("开始制图")
	var (
		fontSize float64 = 24
		pageWidth int = 800
		pageHeight int = 1000
		pagePadding int = 60
		lineSpace float64 = 20
		optionSpace float64 = 0
		questionSpace float64 = 50
		maxCols int = 25
	)

	titleRune := []rune(*title)
	titleRow := int(math.Ceil(float64(len(titleRune))/float64(maxCols)))


	_oStr := make([]string,4)
	for _i,_option := range *options{
		_oStr[_i] = string(65+_i)+". "+_option
	}
	optionStr := strings.Join(_oStr,"    ")


	img := image.NewRGBA(image.Rect(0, 0, pageWidth, pageHeight))
	draw.Draw(img, img.Bounds(), image.White, image.ZP, draw.Src)
	//拷贝一个字体文件到运行目录
	fontBytes, err := ioutil.ReadFile("simsun.ttc")
	if err != nil {
		log.Println(err)
		go log2.ErrorPrint(err.Error())
	}
	font, err := freetype.ParseFont(fontBytes)
	if err != nil {
		log.Println(err)
		go log2.ErrorPrint(err.Error())
	}
	f := freetype.NewContext()
	f.SetDPI(72)
	f.SetFont(font)
	f.SetFontSize(fontSize)
	f.SetClip(img.Bounds())
	f.SetDst(img)
	f.SetSrc(image.Black)

	pt := freetype.Pt(pagePadding, pagePadding)

	for i,_ := range *options{
		for ti:=0;ti<titleRow;ti++{
			_r := (ti+1)*maxCols
			if ti>=titleRow-1{
				_r = len(titleRune)
			}
			index := ""
			answer:=""
			if ti==0{
				index = string(49+i) + ". "
			}
			if ti==titleRow-1{
				answer = "？（ "+string(65+i)+" ）"
			}
			_, err = f.DrawString(index+string(titleRune[ti*maxCols:_r])+answer, pt)
			pt.Y += f.PointToFixed(fontSize+lineSpace)
		}
		pt.Y += f.PointToFixed(fontSize+optionSpace)
		_, err = f.DrawString(optionStr, pt)
		pt.Y += f.PointToFixed(fontSize+questionSpace)
	}


	return img

}

func SaveImage(path *string,img image.Image){
	go log2.LogPrint("保存图片")
	newfile, _ := os.Create(*path)
	defer newfile.Close()


	err := jpeg.Encode(newfile, img, &jpeg.Options{100})
	if err != nil {
		log.Println(err)
		go log2.ErrorPrint(err.Error())
	}
}
